package com.store.app.activity;


import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hyphenate.easeui.model.DBHelper_hy;
import com.hyphenate.easeui.model.recordBean_hy;
import com.store.app.BaseActivity;
import com.store.app.ExitApplication;
import com.store.app.R;
import com.store.app.bean.EventBusBean;
import com.store.app.bean.WypGoodsBean;
import com.store.app.http.Stores;
import com.store.app.imlife.activity.ChatActivity;
import com.store.app.imlife.utils.ToastTools;
import com.store.app.utils.GoToLogin;
import com.store.app.utils.OpenTaoBaoApp;
import com.store.app.utils.SettingData;
import com.store.app.utils.Utils;
import com.store.app.widget.BookedOnlinePopupWindow;
import com.store.app.widget.ProgressWebView;

import org.json.JSONObject;

import java.io.Serializable;

import de.greenrobot.event.EventBus;

/**
 * 嵌网页页面
 * 我要批详情页面
 */
public class WebViewBookedDetailsActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener {
    private TextView tv, tv_right;
    private ProgressWebView webView;
    private String title;
    private String urls = "", id = "";
    private LinearLayout btn_back, lin_right;
    private ProgressBar progressBar;
    private SwipeRefreshLayout mSwipeLayout;
    private LinearLayout lin_all;
    private RelativeLayout loadfail;
    private LinearLayout lin_loadNull;//加载为空
    private LinearLayout lin_loadfail;  //无网络页面
    private TextView tvReload;
    private BookedOnlinePopupWindow bp_online;
    private PopupWindow mPop;
    private final int POST_SUCC = 8;
    private final int POST_FAIL = 9;
    private String errorMsg;
    private String from;
    private GoToLogin goToLogin;
    private String goods_id;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case POST_SUCC:
                    dismissProgressDialog();
                    Intent intent = new Intent(WebViewBookedDetailsActivity.this, TheSingleOrderActivity.class);
                    intent.putExtra("showFragmentIndex", "1");
                    startActivity(intent);
                    Toast.makeText(WebViewBookedDetailsActivity.this, "您的订单已提交，供应商将安排工作人员在24小时内确认订单并协商配送事宜，谢谢合作。", Toast.LENGTH_LONG).show();
                    break;
                case POST_FAIL:
                    dismissProgressDialog();
                    if (!TextUtils.isEmpty(errorMsg)) {
                        Toast.makeText(WebViewBookedDetailsActivity.this, errorMsg, Toast.LENGTH_LONG).show();
                    }

                    break;
            }
        }
    };
    private TextView tv_contact;
    private TextView tv_shopping_car;
    private TextView tv_sell_number;
    private TextView tv_join_car;
    private TextView tv_hpt;
    private TextView tv_close;
    private RelativeLayout rl_dialog_wechat_code;
    public WebViewBookedDetailsActivity() {
        super();
    }

    //数据库存储
    private DBHelper_hy db=null;
    private recordBean_hy rb=null;


    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ExitApplication.getInstance().addActivity(this);
        setContentView(R.layout.activity_webview_details);
        initView();
        if(db==null){
            db=new DBHelper_hy(this);
            rb=new recordBean_hy();
        }

        urls = getIntent().getStringExtra("url");
        try {
            Uri uri = Uri.parse(urls);
            goods_id = uri.getQueryParameter("goods_id");
        } catch (Exception e) {
            
        }

        title = getIntent().getStringExtra("title");
        EventBus.getDefault().register(this);
        try {
            from = getIntent().getStringExtra("from");
        } catch (Exception e) {
        }
        Log.v("zyl", "urls:" + urls);

        goToLogin = new GoToLogin(this);
        findViews();
        setWebView();

    }


    private void setWebView() {
        webView.clearCache(true);
        webView.loadUrl(urls);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setLoadsImagesAutomatically(true);
        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setDefaultTextEncodingName("utf-8");
        webView.getSettings().setLayoutAlgorithm(LayoutAlgorithm.NORMAL);
        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);//设置不使用缓存
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }


        webView.setWebViewClient(new WebViewClient1());
        webView.setWebChromeClient(new WebChromeClient1());
        webView.addJavascriptInterface(new JSInterface(), "jsObj");


    }

    @Override
    public void finish() {
        super.finish();
        EventBus.getDefault().post(new EventBusBean(209));
    }

    private void initView() {
        tv_contact = (TextView) findViewById(R.id.tv_contact);
        tv_contact.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {

                String chatid = "wypcustomerserviceagent";
                String title="官方客服";
                String hand="https://oss-img.meitianhui.com/communityDocs/kefu.jpg";
                Intent intent = new Intent(WebViewBookedDetailsActivity.this, ChatActivity.class);
                intent.putExtra("userId", chatid);
                intent.putExtra("groupName", title);
                startActivity(intent);

                try {
                    rb.saveMember(db, "", chatid, title
                            , "",hand, "0");
                }catch (Exception e){

                }
            }
        });
        tv_shopping_car = (TextView) findViewById(R.id.tv_shopping_car);
        tv_shopping_car.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if(WebViewBookedActivity.shoppingInfoList==null){
                    return;
                }
                if (WebViewBookedActivity.shoppingInfoList.size() == 0) {
                    ToastTools.showShort(WebViewBookedDetailsActivity.this, "请添加商品到购物车！");
                    return;
                }
                Intent intent2 = new Intent(WebViewBookedDetailsActivity.this, ShoppingCarActivity.class);
                Log.v("zyl", "shoppingInfoList size:" + WebViewBookedActivity.shoppingInfoList.size());
                intent2.putExtra("listData", (Serializable) WebViewBookedActivity.shoppingInfoList);
                startActivity(intent2);
            }
        });
        tv_sell_number = (TextView) findViewById(R.id.tv_sell_number);
        tv_join_car = (TextView) findViewById(R.id.tv_join_car);
        tv_join_car.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!TextUtils.isEmpty(goods_id)) {
                    bp_online = new BookedOnlinePopupWindow(goods_id);
                    mPop = bp_online.getPopupWindow(WebViewBookedDetailsActivity.this);
                    WindowManager.LayoutParams lp = getWindow().getAttributes();
                    lp.alpha = 0.7f;
                    getWindow().setAttributes(lp);
                    mPop.showAtLocation(lin_all, Gravity.BOTTOM, 0, 0);
                    bp_online.setonDisMissListener(new BookedOnlinePopupWindow.DisMissListener() {
                        @Override
                        public void dissmiss() {
                            WindowManager.LayoutParams lp = getWindow().getAttributes();
                            lp.alpha = 1f;
                            getWindow().setAttributes(lp);
                        }
                    });
                    bp_online.setonPostListener(new BookedOnlinePopupWindow.PostListener() {
                        @Override
                        public void post(final WypGoodsBean bookedBean, final int num, final String money) {

                            if (Integer.parseInt(bookedBean.getSale_qty()) < num) {
                                Toast.makeText(WebViewBookedDetailsActivity.this, "库存不足！", Toast.LENGTH_SHORT).show();
                                return;
                            }
                            String s_pay_way = bookedBean.getPayment_way();
                            if (s_pay_way.equals("online")) {
                                bookedBean.setBuyCount(num);
                                EventBus.getDefault().post(bookedBean);
                                mPop.dismiss();


                                int number = WebViewBookedActivity.getShoppingNumber();
                                if (number == 0) {
                                    tv_sell_number.setVisibility(View.GONE);
                                } else {
                                    tv_sell_number.setText(number + "");
                                    tv_sell_number.setVisibility(View.VISIBLE);
                                }
                            } else if (s_pay_way.equals("offline")) {
                                AlertDialog.Builder builder = new AlertDialog.Builder(WebViewBookedDetailsActivity.this);
                                builder.setMessage("您确认要提交该订单货到付款吗？")
                                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                mPop.dismiss();
                                            }
                                        });
                                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        mPop.dismiss();
                                        Toast.makeText(WebViewBookedDetailsActivity.this, "订单提交中...", Toast.LENGTH_SHORT).show();
//                                        new PostGoodsInfo(num, money, bookedBean).start();
                                    }
                                });
                                builder.show();
                            }
                        }
                    });
                } else {
                    ToastTools.showShort(WebViewBookedDetailsActivity.this, "获取不到商品id！");
                }
            }
        });
        tv_hpt = (TextView) findViewById(R.id.tv_hpt);
        tv_hpt.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!TextUtils.isEmpty(goods_id)) {
                    Intent intent = new Intent(WebViewBookedDetailsActivity.this, HuoPingCreateActivity.class);
                    intent.putExtra("goods_id", goods_id);
                    startActivity(intent);
                } else {
                    ToastTools.showShort(WebViewBookedDetailsActivity.this, "获取不到商品id");
                }
            }
        });
        int number = WebViewBookedActivity.getShoppingNumber();
        if (number == 0) {
            tv_sell_number.setVisibility(View.GONE);
        } else {
            tv_sell_number.setText(number + "");
            tv_sell_number.setVisibility(View.VISIBLE);
        }
        rl_dialog_wechat_code = (RelativeLayout) findViewById(R.id.rl_dialog_wechat_code);
        RelativeLayout rl_content = (RelativeLayout) findViewById(R.id.rl_content);
        rl_content.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });
        rl_dialog_wechat_code.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                rl_dialog_wechat_code.setVisibility(View.GONE);
            }
        });
        tv_close = (TextView) findViewById(R.id.tv_close);
        tv_close.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                rl_dialog_wechat_code.setVisibility(View.GONE);
            }
        });

    }

    final class JSInterface {

        private Handler handler = new Handler();
        @JavascriptInterface
        public void goToWypCategory(final String category) {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    Intent intent = new Intent(WebViewBookedDetailsActivity.this, WebViewWYPSearchActivity.class);
                    String url = SettingData.http + SettingData.wypURL_classify + Stores.area_id + "&category=" + category;
                    intent.putExtra("url", url);
                    startActivity(intent);
                }
            }, 0);
        }
        @JavascriptInterface
        public void storeGetFreeSucc() {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    Log.v("zyl", "店东领取成功，跳转到订单页面");
                    Intent intent = new Intent(WebViewBookedDetailsActivity.this, TheSingleOrderActivity.class);
                    intent.putExtra("showFragmentIndex", "2");//2代表免费领样的Fragment
                    startActivity(intent);
                }
            }, 0);
        }

        @JavascriptInterface
        public void scan(final String string) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    Log.v("zyl", "scan:" + string);
                    try {
                        JSONObject jsonObject = new JSONObject(string);
                        String goods_code = jsonObject.getString("goods_code");
                        String goods_url = jsonObject.getString("goods_url");
                        String amount = jsonObject.getString("amount");
                        Intent intent = new Intent(WebViewBookedDetailsActivity.this, FreeScanActivity.class);
                        intent.putExtra("goods_code", goods_code);
                        intent.putExtra("goods_url", goods_url);
                        intent.putExtra("amount", amount);
                        startActivity(intent);
                    } catch (Exception e) {
                    }

                }
            });
        }

        @JavascriptInterface
        public void buyGoods(final String string) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    Log.v("zyl", "buyGoods:" + string);
                    String goods_id = string;

                    return;
                }
            });


        }

        @JavascriptInterface
        public void openTaobao(final String taokouling) {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    Log.v("zyl", "获取淘口令：" + taokouling);
                    OpenTaoBaoApp.open(getApplicationContext(), taokouling);

                }
            }, 0);
        }

        @JavascriptInterface
        public void initiateGroup(final String id) {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    Intent intent = new Intent(WebViewBookedDetailsActivity.this, HuoPingCreateActivity.class);
                    intent.putExtra("goods_id", id);
                    startActivity(intent);
                }
            }, 0);
        }

        // 供JS调用
        public void logout(String str) {

        }
        //打开广告页
        @JavascriptInterface
        public void openAdLayer(final String jsonData) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    Log.v("zyl", "openAdLayer jsonData:" + jsonData);
                    try {
                        JSONObject jsonObject = new JSONObject(jsonData);
                        String url = jsonObject.getString("url");
                        Intent intent = new Intent(WebViewBookedDetailsActivity.this, WebViewAdActivity.class);
                        intent.putExtra("url", url);
                        startActivity(intent);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            });
        }
    }


    public void showLoadResult(int state) {
        //无网络情况
        if (state == 1) {
            loadfail.setVisibility(View.VISIBLE);
            lin_loadfail.setVisibility(View.VISIBLE);
            lin_loadNull.setVisibility(View.GONE);
        }//无数据情况
        else if (state == 2) {
            Log.v("zyl", "无数据");
            loadfail.setVisibility(View.VISIBLE);
            lin_loadfail.setVisibility(View.GONE);
            lin_loadNull.setVisibility(View.VISIBLE);
        }//都不显示
        else {
            loadfail.setVisibility(View.GONE);
        }
    }


    public class WebViewClient1 extends WebViewClient {
        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {                 // Handle the error
            Log.v("zyl", "onReceivedError网络加载不出来");

//            webView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);

            //停止webView的所有操作
            webView.onPause();
            webView.pauseTimers();

//			lin_loadfail.setVisibility(View.VISIBLE);
            showLoadResult(1);

        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Log.v("zyl", "shouldOverrideUrlLoading:" + url);

            if (url.contains("/wholesale/detail")) {
                Log.v("zyl", "包含");
                Intent intent = new Intent(WebViewBookedDetailsActivity.this, WebViewBookedDetailsActivity.class);
                intent.putExtra("url", url);
                intent.putExtra("title", title);
                startActivity(intent);
            } else {
                Log.v("zyl", "不包含");
                view.loadUrl(url);
            }

            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {

            super.onPageStarted(view, url, favicon);
            Log.v("zyl", "onPageStart:" + url);


        }

        @Override
        public void onPageFinished(WebView view, String url) {
            if (url.startsWith("http")) {
                urls = url;
            }
        }


    }

    public class WebChromeClient1 extends WebChromeClient {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            Log.v("zyl", "加载进度：" + newProgress);
            if (newProgress == 100) {
                progressBar.setVisibility(View.GONE);
            } else {
                if (progressBar.getVisibility() == View.GONE)
                    progressBar.setVisibility(View.VISIBLE);
                progressBar.setProgress(newProgress);
            }
            super.onProgressChanged(view, newProgress);
        }

    }

    public void onPause() {//继承自Activity
        super.onPause();
        webView.onPause();

        webView.pauseTimers();
        if (isFinishing()) {
            webView.loadUrl("about:blank");
            setContentView(new FrameLayout(this));
        }
    }

    public void onResume() {//继承自Activity
        super.onResume();
        webView.onResume();
        webView.resumeTimers();
    }

    private void findViews() {
        lin_right = (LinearLayout) findViewById(R.id.public_ll_right);
        lin_right.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
//				if(title.equals("免费领")){
//					Log.v("zyl","是惠金币类型");
//					startActivity(new Intent(WebViewBookedActivity.this,GoldBalanceActivity.class));
//				}else{
                finish();
//				}
            }
        });
        tv_right = (TextView) findViewById(R.id.public_tv_right);
        tv_right.setVisibility(View.GONE);
//		if(title.equals("免费领")){
//			tv_right.setText("金币明细");
//		}else{
//			tv_right.setText("关闭");
        tv_right.setBackgroundResource(R.drawable.pic_icon_close_x);
//		}

        if ("WebViewSearchActivity".equals(from)) {
            lin_right.setVisibility(View.INVISIBLE);
        } else {
            lin_right.setVisibility(View.VISIBLE);
        }
        progressBar = (ProgressBar) findViewById(R.id.progressbar);
        loadfail = (RelativeLayout) findViewById(R.id.loadfail);

        lin_loadfail = (LinearLayout) findViewById(R.id.ll_load_fail);//无网络
        lin_loadNull = (LinearLayout) findViewById(R.id.ll_load_null);//无数据
        tvReload = (TextView) findViewById(R.id.tv_reload);
        tvReload.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Utils.isFastClick()) {
                    return;
                }
                showLoadResult(3);
                webView.clearCache(true);
                webView.clearHistory();
                webView.clearFormData();
                webView.loadUrl(urls);
            }
        });
        lin_all = (LinearLayout) findViewById(R.id.lin_all);
        webView = (ProgressWebView) findViewById(R.id.onlcon_web);
        webView.setContext(this);

        tv = (TextView) findViewById(R.id.tvTitle);
        tv.setText(title);
        findViewById(R.id.public_ll_return).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (webView.canGoBack() && !"about:blank".equals(webView.getUrl())) {
                    webView.goBack();// 返回前一个页面
                } else {
                    finish();
                }
            }
        });
//		lin_loadfail.setOnClickListener(new OnClickListener() {
//			@Override
//			public void onClick(View v) {
//				lin_loadfail.setVisibility(View.GONE);
//				webView.clearCache(true);
//				webView.clearHistory();
//				webView.clearFormData();
//				webView.loadUrl(urls);
//			}
//		});

        mSwipeLayout = (SwipeRefreshLayout) findViewById(R.id.sw);
        mSwipeLayout.setOnRefreshListener(this);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack() && !"about:blank".equals(webView.getUrl())) {
            webView.goBack();// 返回前一个页面
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    private void onEvent(EventBusBean eventBusBean) {
        if (eventBusBean.type == 210) {
            int number = WebViewBookedActivity.getShoppingNumber();
            if (number == 0) {
                tv_sell_number.setVisibility(View.GONE);
            } else {
                tv_sell_number.setText(number + "");
                tv_sell_number.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public void onRefresh() {
        setWebView();
        mSwipeLayout.setRefreshing(false);
    }

}
